package edu.neu.ecommerceplatform.service.Impl;

import edu.neu.ecommerceplatform.Exception.DuplicateResourceException;
import edu.neu.ecommerceplatform.Exception.ResourceNotFoundException;
import edu.neu.ecommerceplatform.dto.CreateUserRequest;
import edu.neu.ecommerceplatform.mapper.UserMapper;
import edu.neu.ecommerceplatform.model.User;
import edu.neu.ecommerceplatform.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    private final UserMapper userMapper;

    @Autowired
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public User getUserByName(String name){
        logger.info("正在尝试通过用户名获取用户 name:{}",name);
        User user = userMapper.findByName(name);
        if (user == null) {
            logger.warn("未找到用户 name:{}",name);
            throw new ResourceNotFoundException("User","name",name);
        }
        logger.info("成功找到用户 name:{}",name);
        return user;
    }

    @Override
    public User getUserByPhone(String phone_number){
        logger.info("正在尝试通过手机号获取用户 phone_number:{}",phone_number);
        User user = userMapper.findByPhone(phone_number);
        if (user == null) {
            logger.warn("未找到用户 phone_number:{}",phone_number);
            throw new ResourceNotFoundException("User","phone_number",phone_number);
        }
        logger.info("成功找到用户 phone_number:{}",phone_number);
        return user;
    }

    @Override
    public User getUserById(Integer id) {
        logger.info("正在尝试通过ID获取用户 ID:{}", id);
        User user = userMapper.findById(id);
        if (user == null) {
            logger.warn("未找到用户 ID:{}", id);
            throw new ResourceNotFoundException("User", "id", id);
        }
        logger.info("成功找到用户 ID:{}", id);
        return user;
    }

    @Transactional
    @Override
    public User updateNameByPhone(String phoneNumber, String name) {
        logger.info("正在尝试更新用户昵称通过手机号，手机号:{}，新昵称:{}",phoneNumber,name);

        User user = userMapper.findByPhone(phoneNumber);
        if(user == null) {
            logger.warn("无法找到用户手机号:{}",phoneNumber);
            throw new ResourceNotFoundException("User","phoneNumber",phoneNumber);
        }
        User userWithSameName = userMapper.findByName(name);
        if (userWithSameName != null){
            logger.warn("用户名已存在:{}", name);
            throw new DuplicateResourceException("用户名" + name + "已存在");
        }
        user.setName(name);
        int updatedRows = userMapper.updateNameByPhone(phoneNumber,name);
        if(updatedRows == 0){
            logger.error("更新用户name失败:{}",name);
            throw new RuntimeException("更新用户name失败。");
        }

        logger.info("成功更新用户昵称通过手机号，手机号:{}，新昵称:{}",phoneNumber,name);
        return user;
    }
    @Transactional
    @Override
    public User createUser(CreateUserRequest createUserRequest) {
        logger.info("正在添加新用户,电话:{},昵称:{}",createUserRequest.getName(),createUserRequest.getPhoneNumber());

        User userFromPhone = userMapper.findByPhone(createUserRequest.getPhoneNumber());
        if(userFromPhone != null) {
            logger.warn("正在添加的用户电话已经存在,电话:{}",createUserRequest.getPhoneNumber());
            throw new DuplicateResourceException("正在添加的用户电话已经存在");
        }
        User userFromName = userMapper.findByName(createUserRequest.getName());
        if (userFromName != null){
            logger.warn("正在添加的用户昵称已经存在,昵称:{}",createUserRequest.getName());
            throw new DuplicateResourceException("正在添加的用户昵称已经存在");
        }

        User user = new User(null,createUserRequest.getName(),createUserRequest.getPhoneNumber());

        int insertedRows = userMapper.save(user);
        if(insertedRows == 0){
            logger.error("创建用户失败，未插入任何行。");
            throw new RuntimeException("创建用户失败，请稍后重试。");
        }
        logger.info("成功创建用户: {}, ID: {}", user.getName(), user.getId());
        return user;
    }

    @Override
    public List<User> getAllUsers() {
        logger.info("正在获取全部用户");
        return userMapper.findAll();
    }

    @Override
    public List<User> getUsersByProductId(Integer productId) {
        logger.info("正在根据商品ID查询购买用户，productId:{}", productId);
        List<User> users = userMapper.findUsersByProductId(productId);
        logger.info("查询到 {} 个用户购买了此商品", users.size());
        return users;
    }

    @Override
    public void deleteUser(Integer id) {
        logger.info("正在尝试删除用户 ID: {}", id);
        User user = userMapper.findById(id);
        if (user == null) {
            logger.warn("无法找到要删除的用户 ID: {}", id);
            throw new ResourceNotFoundException("User", "id", id);
        }
        userMapper.deleteById(id);
        logger.info("成功删除用户 ID: {}", id);
    }
}
